<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>新增/编辑内容</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.15.9/theme-chalk/index.css">
    <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
    <link rel="icon" href="http://dev.admin.front.tea.p.yufeiworld.com/favicon.ico">
    <style>
        #editor—wrapper {
            border: 1px solid #ccc;
            z-index: 100; /* 按需定义 */
        }

        #toolbar-container {
            border-bottom: 1px solid #ccc;
        }

        #editor-container {
            height: 300px;
        }

        .inputClass {
            width: 250px;
        }

        .dialog-footer {
            position: relative;
            left: 400px;
        }
    </style>
</head>
<body>
<div id="app" style="width: 1000px; margin: 0 auto">
    <div style="margin-top: 20px;">
        <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 18px;">
            <el-breadcrumb-item :to="{ path: '/' }">
                <i class="el-icon-picture-outline"></i> 新增/编辑内容
            </el-breadcrumb-item>
        </el-breadcrumb>
    </div>

    <el-divider></el-divider>

    <div>
        <el-card class="box-card">
            <el-form :model="contentData" label-width="120px">
                <el-form-item label="文章标题：">
                    <el-input v-model="contentData.title" autocomplete="off" class="inputClass"></el-input>
                </el-form-item>
                <el-form-item label="文章分类：">
                    <el-select v-model="contentData.categoryId" placeholder="请选择分类">
                        <el-option
                                v-for="category in categorys"
                                :key="category.value"
                                :label="category.label"
                                :value="category.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文章标签：">
                    <el-select v-model="selectKeywords" multiple placeholder="请选择标签">
                        <el-option
                                v-for="keyword in keywords"
                                :key="keyword.value"
                                :label="keyword.label"
                                :value="keyword.value + ',' + keyword.label">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文章摘要：">
                    <el-input v-model="contentData.brief" autocomplete="off" class="inputClass"></el-input>
                </el-form-item>
                <el-form-item label="排序序号：">
                    <el-input v-model="contentData.sort" autocomplete="off" class="inputClass"></el-input>
                </el-form-item>
                <el-form-item label="文章封面：">
                    <el-upload
                            action="/picture/fileUpload"
                            name="file"
                            limit="1"
                            ref="upload"
                            list-type="picture-card"
                            :file-list="fileList"
                            :on-success="handleSuccess"
                            :on-remove="handleRemove"
                            :on-exceed="handleExceed">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="文章详情：">
                    <div id="editor—wrapper">
                        <div id="toolbar-container"><!-- 工具栏 --></div>
                        <div id="editor-container"><!-- 编辑器 --></div>
                    </div>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" style="margin: 0 auto">
                <el-button @click="window.history.go(-1)">返 回</el-button>
                <el-button type="primary" @click="submitForm()">确 定</el-button>
            </div>
        </el-card>
    </div>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<!-- import Vue before Element -->
<script src="https://cdn.staticfile.org/vue/2.6.14/vue.min.js"></script>
<!-- import JavaScript -->
<script src="https://cdn.staticfile.org/element-ui/2.15.9/index.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.9.3/qs.min.js"></script>
<!-- 引入富文本 -->
<script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
<script>
    let v = new Vue({
        el: '#app',
        data: function () {
            return {
                contentData: {
                    id: null,
                    title: '',
                    categoryId: '',
                    keywords: '',
                    brief: '',
                    coverUrl: '',
                    sort: '',
                    detail: ''
                },
                fileList: [],
                categorys: [{
                    value: 1,
                    label: '花茶'
                }, {
                    value: 2,
                    label: '红茶'
                }, {
                    value: 3,
                    label: '绿茶'
                }, {
                    value: 4,
                    label: '常识'
                }, {
                    value: 5,
                    label: '功效'
                }],
                keywords: [{
                    value: 1,
                    label: '茶叶'
                }, {
                    value: 2,
                    label: '红茶'
                }, {
                    value: 3,
                    label: '绿茶'
                }, {
                    value: 4,
                    label: '花茶'
                }],
                selectKeywords: [],
                editor: null
            }
        },
        methods: {
            handleSuccess(response, file, fileList) {
                v.contentData.coverUrl = response.data
            },
            handleRemove(file, fileList) {
                v.contentData.coverUrl = ''
            },
            handleExceed(files, fileList) {
                v.$message.error("不支持批量图片上传");
            },
            //提交表单
            submitForm() {
                //处理选中的keywords的格式
                let selectKeywords = v.selectKeywords;
                let handlerBeforeSelectKeywords = [];
                for (let i = 0; i < selectKeywords.length; i++) {
                    let everyKeywords = selectKeywords[i].split(",");
                    let keyword = {
                        "id": everyKeywords[0],
                        "name": everyKeywords[1]
                    }
                    handlerBeforeSelectKeywords.push(keyword);
                }
                v.contentData.keywords = JSON.stringify(handlerBeforeSelectKeywords);
                let formData = window.Qs.stringify(v.contentData);

                //判断是新增还是修改操作
                if (!v.contentData.id) {
                    axios.post('/content/save', formData).then(function (response) {
                        if (response.data.code === 0) {
                            v.$message({
                                message: '新增文章内容成功！',
                                type: 'success'
                            });
                            setTimeout(() => {
                                window.location.href = "/index.html"
                            }, 2000);
                        } else {
                            v.$message.error(response.data.data);
                        }
                    })
                } else {
                    axios.post('/content/update', formData).then(function (response) {
                        if (response.data.code === 0) {
                            v.$message({
                                message: '修改文章内容成功！',
                                type: 'success'
                            });
                            setTimeout(() => {
                                window.location.href = "/index.html"
                            }, 2000);
                        } else {
                            v.$message.error(response.data.data);
                        }
                    })
                }
            },
            //初始化富文本
            async initEditor() {
                const {createEditor, createToolbar} = window.wangEditor

                const editorConfig = {
                    placeholder: '请输入',
                    onChange(editor) {
                        //当富文本发生改变时，将最新内容同步到定义的数据中
                        v.contentData.detail = editor.getHtml();
                    }
                }

                const editor = createEditor({
                    selector: '#editor-container',
                    html: this.contentData.detail,
                    config: editorConfig,
                    mode: 'default'
                })

                const toolbarConfig = {}

                const toolbar = createToolbar({
                    editor,
                    selector: '#toolbar-container',
                    config: toolbarConfig,
                    mode: 'default'
                })
            },
            //初始化数据
            async initData() {
                //如果浏览器地址中有id 则代表是修改操作
                let urlParam = location.search.split("?id=");
                if (urlParam.length <= 1) {
                    return;
                }
                let contentId = urlParam[1];
                const response = await axios.get('/content/detail?contentId=' + contentId);
                //处理所有响应数据
                this.contentData = response.data.data
                //回显图片设置
                let imgUrl = {
                    "url": this.contentData.coverUrl
                }
                this.fileList.push(imgUrl)
                //回显标签设置
                let keywordsJson = JSON.parse(this.contentData.keywords);
                for (let i = 0; i < keywordsJson.length; i++) {
                    let selectedKeyword = keywordsJson[i].id + "," + keywordsJson[i].name
                    this.selectKeywords.push(selectedKeyword);
                }
            }
        },
        async mounted() {
            //初始化数据
            await this.initData();
            //初始化富文本
            await this.initEditor();
        }
    })
</script>
</html>